package com.hdax.search.service.impl;




import com.alibaba.fastjson.JSON;
import com.hdax.common.to.es.SkuEsModel;
import com.hdax.common.utils.R;
import com.hdax.search.EsConstant.EsConstant;
import com.hdax.search.config.ElasticSearchConfig;
import com.hdax.search.feign.ProductFeignService;
import com.hdax.search.service.MillSeatchService;
import com.hdax.search.vo.SearchResult;
import com.hdax.search.vo.SeatchParam;
import com.mysql.cj.x.protobuf.MysqlxDatatypes;
import org.apache.commons.lang.StringUtils;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.swing.text.Highlighter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class MillSeatchServiceimpl implements MillSeatchService{

    @Autowired
    private RestHighLevelClient client;

    @Autowired
    private ProductFeignService productFeignService;



    /**
     * 检索商品
     * 返回检索结果
     * @param seatchParam
     * @return
     */
    @Override
    public SearchResult search(SeatchParam seatchParam) {
        //根据页面传递过来的参数，去es中检索商品
        SearchResult result=null;
        //1、准备检索的请求
        SearchRequest searchRequest = buildSearchRequest(seatchParam);
        try {
            //执行检索请求
            SearchResponse search = client.search(searchRequest, ElasticSearchConfig.COMMON_OPTIONS);
            //分析响应数据，封装成我们需要的格式
            result=builSearchResult(search,seatchParam);
            //当前页
            result.setPageNum(seatchParam.getPageNum());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return result;
    }

    /**
     * 构建结构数据
     * @param search
     * @return
     */
    private SearchResult builSearchResult(SearchResponse search,SeatchParam seatchParam) {

        /**
         * 响应数据对象
         */
        SearchResult searchResult=new SearchResult();
        SearchHits hits = search.getHits();
        List<SkuEsModel> skuEsModels=new ArrayList<>();
        if(hits.getHits()!=null&&hits.getHits().length>0){
            for (SearchHit hit : hits.getHits()) {
                String sourceAsString = hit.getSourceAsString();
                SkuEsModel skuEsModel1 = JSON.parseObject(sourceAsString, SkuEsModel.class);
                skuEsModels.add(skuEsModel1);
            }
        }
        searchResult.setProducts(skuEsModels);

        /**
         * 查询所有商品关联的所有属性信息
         */
        List<SearchResult.AttrVo> attrVos=new ArrayList<>();
        ParsedNested attr_agg = search.getAggregations().get("attr_agg");
        ParsedLongTerms attr_id_agg =attr_agg.getAggregations().get("attr_id_agg");
        List<? extends Terms.Bucket> buckets2 = attr_id_agg.getBuckets();
        for (Terms.Bucket bucket : buckets2) {
            SearchResult.AttrVo attrVo=new SearchResult.AttrVo();
            //属性的id
            long l = bucket.getKeyAsNumber().longValue();
            attrVo.setAttrId(l);
            //属性的名称
            ParsedStringTerms attr_name_agg = bucket.getAggregations().get("attr_name_agg");
            String keyAsString = attr_name_agg.getBuckets().get(0).getKeyAsString();
            attrVo.setAttrName(keyAsString);
            //属性值
            ParsedStringTerms attr_value_agg = bucket.getAggregations().get("attr_value_agg");
            List<String> collect = attr_value_agg.getBuckets().stream().map(item -> {
                String keyAsString1 = item.getKeyAsString();
                return keyAsString1;
            }).collect(Collectors.toList());
            attrVo.setAttrValue(collect);
            attrVos.add(attrVo);
        }
        searchResult.setAttrs(attrVos);
        /**
         * 当前所有商品涉及到的所有品牌信息
         */
        List<SearchResult.BrandVo> brandVos=new ArrayList<>();
        ParsedLongTerms brand_agg = search.getAggregations().get("brand_agg");
        List<? extends Terms.Bucket> buckets1 = brand_agg.getBuckets();
        for (Terms.Bucket bucket : buckets1) {
            SearchResult.BrandVo brandVo=new SearchResult.BrandVo();
            //得到品牌的id
            long l = bucket.getKeyAsNumber().longValue();
            brandVo.setBrandId(l);
            //品牌的名称
            ParsedStringTerms brand_name_agg = bucket.getAggregations().get("brand_name_agg");
            String brandName = brand_name_agg.getBuckets().get(0).getKeyAsString();
            brandVo.setBrandName(brandName);
            //品牌的图片
            ParsedStringTerms brand_img_agg = bucket.getAggregations().get("brand_img_agg");
            String brandImg = brand_img_agg.getBuckets().get(0).getKeyAsString();
            brandVo.setBrandImg(brandImg);
            brandVos.add(brandVo);
        }
        searchResult.setBrands(brandVos);
        /**
         * 查询当前商品设计到的所有分类信息
         */
        ParsedLongTerms aggregations = search.getAggregations().get("catalog_agg");
        List<SearchResult.CatalogVo> catalogVos=new ArrayList<>();
        List<? extends Terms.Bucket> buckets = aggregations.getBuckets();
        for (Terms.Bucket bucket : buckets) {
            SearchResult.CatalogVo catalogVo = new SearchResult.CatalogVo();
            //分类的id
            String keyAsString = bucket.getKeyAsString();
            catalogVo.setCatalogId(Long.valueOf(keyAsString));
            //分类的名称
            ParsedStringTerms aggregations1 = bucket.getAggregations().get("catalog_name_agg");
            String catalogName = aggregations1.getBuckets().get(0).getKeyAsString();
            catalogVo.setCatalogName(catalogName);
            catalogVos.add(catalogVo);
        }
        searchResult.setCatalogs(catalogVos);
        /**
         * 分页信息
         */
        //命中的总记录数
        long total=hits.getTotalHits().value;
        searchResult.setTotal(total);
        //总页码
        int totalPages = (int) (total%EsConstant.PRODUCT_PAGESIEZ==0?total/EsConstant.PRODUCT_PAGESIEZ:(total/EsConstant.PRODUCT_PAGESIEZ+1));
        searchResult.setTotalPages(totalPages);
        //页码
        List<Integer>  pageNavs=new ArrayList<>();
        for(int i=1;i<=totalPages;i++){
            pageNavs.add(i);
        }
        searchResult.setPageNavs(pageNavs);


        /**
         * 面包屑导航的数据
         */
//        List<SearchResult.NavVo> navVos=new ArrayList<>();
//        if(seatchParam.getAttrs()!=null&&seatchParam.getAttrs().size()>0){
//            navVos = seatchParam.getAttrs().stream().map(item -> {
//                SearchResult.NavVo navVo = new SearchResult.NavVo();
//                String[] s = item.split("_");
//                navVo.setNavValue(s[1]);
//                R info = productFeignService.info(Long.parseLong(s[0]));
//                int code= (int) info.get("code");
//                if(code==0){
//                    Object data = info.getData();
//                    System.out.println(data);
//                }
//                return navVo;
//            }).collect(Collectors.toList());
//        }
//        searchResult.setNavs(navVos);
        return searchResult;
    }

    /**
     * 准备检索请求
     * @return
     */

    private SearchRequest buildSearchRequest(SeatchParam seatchParam){

        //构建DSL语句
        SearchSourceBuilder searchSourceBuilder=new SearchSourceBuilder();

        /**
         * 模糊匹配，过滤(按照属性，分类，品牌，价格区间，库存)
         */
        //构建bool-》query
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();

        //must->模糊匹配(根据查询的关键字进行模糊匹配)
        if(StringUtils.isNotBlank(seatchParam.getKeyword())){
            boolQuery.must(QueryBuilders.matchQuery("skuTitle",seatchParam.getKeyword()));
        }
        //过滤(按照三级分类的id进行过滤)
        if(seatchParam.getCatalog3Id()!=null){
            boolQuery.filter(QueryBuilders.termQuery("catalogId",seatchParam.getCatalog3Id()));
        }
        //过滤品牌的id进行查询
        if(seatchParam.getBrandId()!=null){
            boolQuery.filter(QueryBuilders.termQuery("brandId",seatchParam.getBrandId()));
        }
        /**
         * 按照所有指定的属性进行查询(过滤)
         *
         * 34_meiy:2020
         */
        if(seatchParam.getAttrs()!=null&&seatchParam.getAttrs().size()>0){
            //嵌入式，ScoreMode.None不进行评分呢
            for (String attr : seatchParam.getAttrs()) {
                BoolQueryBuilder nestbuilder = QueryBuilders.boolQuery();
                //检索条件
                String[] s = attr.split("_");
                //检索属性的id
                String attrId=s[0];
                String[] attrValue=s[1].split(":");
                nestbuilder.must(QueryBuilders.termQuery("attrs.attrId",attrId));
                nestbuilder.must(QueryBuilders.termsQuery("attrs.attrValue",attrValue));
                NestedQueryBuilder attrs = QueryBuilders.nestedQuery("attrs", nestbuilder, ScoreMode.None);
                boolQuery.filter(attrs);
            }
        }
        //按照库存是否有进行查询
        //seatchParam.getHasStock()==1 true  否在就是  false
        if(seatchParam.getHasStock()!=null){
            boolQuery.filter(QueryBuilders.termQuery("hasStock",seatchParam.getHasStock()==1));
        }
        //按照价格区间进行检索
        //_5000
        if (!StringUtils.isEmpty(seatchParam.getSkuPrice())){
            RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("skuPrice");
            String[] s = seatchParam.getSkuPrice().split("_");
            if(s.length==2){
                rangeQueryBuilder.gte(s[0]).lte(s[1]);
            }else if(s.length==1){
                if(seatchParam.getSkuPrice().startsWith("_")){
                    rangeQueryBuilder.lte(s[0]);
                }
                if(seatchParam.getSkuPrice().endsWith("_")){
                    rangeQueryBuilder.gte(s[0]);
                }
            }
            boolQuery.filter(rangeQueryBuilder);
        }
        searchSourceBuilder.query(boolQuery);

        /**
         * 排序
         */
        if(!StringUtils.isEmpty(seatchParam.getSort())){
            String sort = seatchParam.getSort();
            //sort=hostScore_asc/desc
            String[] s = sort.split("_");
            SortOrder order=s[1].equalsIgnoreCase("asc")?SortOrder.ASC:SortOrder.DESC;
            searchSourceBuilder.sort(s[0], order);
        }
        /**
         * 分页
         */
        //当前页-1*每页的条数
        // 0 2
        searchSourceBuilder.from((seatchParam.getPageNum()-1)*EsConstant.PRODUCT_PAGESIEZ);
        searchSourceBuilder.size(EsConstant.PRODUCT_PAGESIEZ);
        /**
         * 高亮
         */
        if(StringUtils.isNotBlank(seatchParam.getKeyword())){
            HighlightBuilder highlightBuilder = new HighlightBuilder();
            highlightBuilder.field("skuTitle");
            highlightBuilder.preTags("<b style='color:red'>");
            highlightBuilder.postTags("</b>");
            searchSourceBuilder.highlighter(highlightBuilder);
        }


        /**
         * 聚合分析
         */
        //品牌的聚合
        TermsAggregationBuilder brand_agg = AggregationBuilders.terms("brand_agg").field("brandId").size(20);
        //品牌聚合的子聚合
        brand_agg.subAggregation(AggregationBuilders.terms("brand_name_agg").field("brandName").size(20));
        brand_agg.subAggregation(AggregationBuilders.terms("brand_img_agg").field("brandImg").size(20));
        searchSourceBuilder.aggregation(brand_agg);
        //分类的聚合
        TermsAggregationBuilder terms = AggregationBuilders.terms("catalog_agg").field("catalogId").size(20);
        terms.subAggregation(AggregationBuilders.terms("catalog_name_agg").field("catalogName").size(1));
        searchSourceBuilder.aggregation(terms);
        //属性的聚合
        NestedAggregationBuilder nested = AggregationBuilders.nested("attr_agg", "attrs");
        TermsAggregationBuilder field = AggregationBuilders.terms("attr_id_agg").field("attrs.attrId").size(20);
        nested.subAggregation(field);
        field.subAggregation(AggregationBuilders.terms("attr_name_agg").field("attrs.attrName").size(1));
        field.subAggregation(AggregationBuilders.terms("attr_value_agg").field("attrs.attrValue").size(20));
        searchSourceBuilder.aggregation(nested);
//        String s = searchSourceBuilder.toString();
//        System.out.println("dddddddddddddddddddd"+s);
        SearchRequest searchRequest = new SearchRequest(new String[]{EsConstant.PRODUCT_INDEX}, searchSourceBuilder);
        return searchRequest;
    }
}
